import React = require("react");
import { DesignView } from "controls/design-view";
import { PageProps } from "maishu-chitu-react";
import { defaultPageDatas } from "services/page-datas";
import { LocalService } from "services/local-service";
import { ProductInfo } from "components/product-info/component";
import { ShoppingService } from "services/shopping";
import { PageDataRecord } from "entities";
import { dataSources } from "services/dataSources";

export default class ProductPage extends React.Component<PageProps> {
    localService: LocalService;
    shoppingService: ShoppingService;
    productId: string;
    designView: DesignView;
    pageDataReocrd: PageDataRecord;

    constructor(props) {
        super(props);

        this.localService = this.props.createService(LocalService);
        this.shoppingService = this.props.createService(ShoppingService);

        let pageData = defaultPageDatas.product();
        this.pageDataReocrd = { pageData, name: "product" } as PageDataRecord;
    }
    componentDidMount() {
        let designViewSave = this.designView.save;
        this.designView.save = async () => {
            console.assert(this.designView.designer.value != null);
            this.designView.designer.value.allComponents().filter(o => o.props != null);
            let c = this.designView.designer.value.findComponetsByTypeName(ProductInfo.name)[0] as ProductInfo;
            console.assert(c != null);

            await dataSources.product.insert(c.props.product);
            console.assert(c.props.product.Id != null);
            this.pageDataReocrd.id = c.props.product.Id;
            return designViewSave.apply(this.designView);
        }
    }
    render() {
        return <DesignView {...{ app: this.props.app }} pageDataRecord={this.pageDataReocrd}
            hidePageSettingPanel={true}
            ref={e => this.designView = this.designView || e}>
        </DesignView>
    }
}